package net.entelijan.cobean.text.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.entelijan.cobean.text.ITextConverter;
import net.entelijan.cobean.text.IllegalTextException;

public class DateTextConverter implements ITextConverter<Date> {

	private SimpleDateFormat dateConverter;

	private transient String pattern;

	public DateTextConverter() {
		super();
		dateConverter = new SimpleDateFormat();
		dateConverter.setLenient(false);
	}

	public DateTextConverter(String pattern) {
		super();
		dateConverter = new SimpleDateFormat(pattern);
		dateConverter.setLenient(false);
		this.pattern = pattern;
	}

	@Override
	public Date convertToObject(String stringValue) throws IllegalTextException {
		try {
			Date re = null;
			if (stringValue != null && !"".equals(stringValue)) {
				re = dateConverter.parse(stringValue);
			}
			return re;
		} catch (ParseException e) {
			throw new IllegalTextException("'" + stringValue
					+ "' is not a valid date" + (pattern == null ? "" : ". Use '" + pattern
					+ "'"));
		}
	}

	@Override
	public String convertToString(Date object) {
		String re = null;
		if (object != null) {
			re = dateConverter.format(object);
		}
		return re;
	}

}
